class SinglyLinkedList2 {
    public Node head = new Node(666,null);

    //头插
    public void addFirst(int value){
        Insert(0,value);
    }

    //遍历
    public void Look(){
        Node tmp = head.next;
        while(tmp != null){
            if (tmp.next == null){
                System.out.print(tmp.value);
            } else {
                System.out.print(tmp.value + "->");
            }
            tmp = tmp.next;
        }
        System.out.println();
    }

    //查尾节点
    public Node FindLast(){
        Node tmp = head;
        while(tmp.next != null){
            tmp = tmp.next;
        }

        return tmp;
    }

    //尾插
    public void addLast(int value)  {
        Node tmp = FindLast();
        tmp.next = new Node(value,null);
    }

    //获取某个节点的值
    public Node FindNode(int num){
        Node tmp = head.next;
        for (int i = 0; tmp != null; i++){
            if (i == num){
                System.out.println("当前节点对应的value为：" + tmp.value);
                return tmp;
            }
            tmp = tmp.next;
        }

        //System.out.println("没找到");
        throw new IllegalArgumentException(num + "不合法，查找失败");
    }

    //获取某个节点的位置
    public Node Find(int num){
        Node tmp = head.next;
        for (int i = 0; tmp != null; i++){
            if (i == num){
                return tmp;
            }
            tmp = tmp.next;
        }

        //System.out.println("没找到");
        throw new IllegalArgumentException(num + "不合法，查找失败");
    }

    //插入到某个位置
    public void Insert(int insert, int val ) {
        if (insert == 0){
            head.next = new Node(val,head.next);
            return;
        }
        Node tmp = Find(insert - 1);
        if (tmp == null){
            throw new IllegalArgumentException(insert + "不合法");
        }

        tmp.next = new Node(val,tmp.next);
    }

    //删除头结点
    public void RemoveFirst(){
        if (head == null){
            throw new IllegalArgumentException( "不合法");

        }

        head = head.next;
    }

    //删除任意结点
    public void Remove(int insert){
        Node tmp = Find(insert - 1);
        if (tmp == null || tmp.next == null){
            throw new IllegalArgumentException(insert + "不合法");
        }
        tmp.next = tmp.next.next;
    }
}

public class MyList2 {
    //带哨兵实现
    public static void main(String[] args) {
        SinglyLinkedList2 singlyLinkedList = new SinglyLinkedList2();
        singlyLinkedList.addFirst(0);
        singlyLinkedList.addFirst(1);
        singlyLinkedList.addFirst(2);
        singlyLinkedList.addFirst(3);
        singlyLinkedList.addFirst(5);
        singlyLinkedList.addLast(0);
        singlyLinkedList.addLast(1);
        singlyLinkedList.addLast(2);
        singlyLinkedList.addLast(3);
        singlyLinkedList.Insert(1,4);
        singlyLinkedList.RemoveFirst();
        singlyLinkedList.Remove(3);
        singlyLinkedList.Look();
        singlyLinkedList.FindNode(3);
    }
}
